﻿/*
 Copyright (c) 2012 Aaron Zhang
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

using SharkCrawler.Scheduler;
using SharkCrawler.Tracing;
using System;
using System.Text;
using System.Windows.Forms;

namespace SharkCrawler
{
    public partial class MainForm : Form, ITracer
    {
        private DefaultScheduler scheduler;
        private OptionForm optionForm;
        private StringBuilder requestBuilder = new StringBuilder();
        private StringBuilder errorBuilder = new StringBuilder();

        public delegate void TraceDelegate(TraceItem trace);
        public delegate void ErrorDelegate(ErrorItem error);

        public MainForm()
        {
            InitializeComponent();
            RegisterEvents();
            TracerSink.Instance.Register(this);
        }

        private void RegisterEvents()
        {
            this.FormClosed += MainForm_FormClosed;
            this.btnResume.Click += btnResume_Click;
            this.btnPause.Click += btnPause_Click;
            this.btnOptions.Click += btnOptions_Click;
            this.optionsToolStripMenuItem.Click += btnOptions_Click;
            this.startToolStripMenuItem.Click += btnGo_Click;
            this.resumeToolStripMenuItem.Click += btnResume_Click;
            this.pauseToolStripMenuItem.Click += btnPause_Click;
        }

        #region Event Handler

        private void btnOptions_Click(object sender, EventArgs e)
        {
            if (optionForm == null)
            {
                optionForm = new OptionForm();
            }
            optionForm.ShowDialog(this);
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (scheduler != null)
                scheduler.Pause();
        }

        private void btnResume_Click(object sender, EventArgs e)
        {
            if (scheduler != null)
                scheduler.Resume();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (scheduler != null)
                scheduler.Stop();
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            tsStatus.Text = string.Empty;
            if (!string.IsNullOrEmpty(cmbUrl.Text))
            {
                if (Uri.IsWellFormedUriString(cmbUrl.Text, UriKind.Absolute))
                {
                    scheduler = new DefaultScheduler(Common.Environment.Instance.ThreadNumber, Common.Environment.Instance.OutputFolder);
                    scheduler.Start(cmbUrl.Text);
                    tsStatus.Text = "Started...";
                }
                else
                {
                    tsStatus.Text = "Invalid Url, an absolute url is required: http://www.microsoft.com";
                }
            }
            else
            {
                tsStatus.Text = "Url cannot be empty.";
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (AboutBox about = new AboutBox())
            {
                about.ShowDialog(this);
            }
        }

        #endregion

        public void Trace(TraceItem trace)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new TraceDelegate(Trace), trace);
            }
            else
            {
                bool found = false;
                for (int i = 0; i < listThreads.Items.Count; i++)
                {
                    if (listThreads.Items[i].SubItems[0].Text == trace.ThreadId)
                    {
                        listThreads.Items[i].SubItems[1].Text = trace.Url;
                        listThreads.Items[i].SubItems[2].Text = trace.Status;
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    ListViewItem item = new ListViewItem();
                    listThreads.Items.Add(item);
                    item.SubItems[0].Text = trace.ThreadId;
                    item.SubItems.Add(trace.Url);
                    item.SubItems.Add(trace.Status);
                }

                if (!string.IsNullOrEmpty(trace.Url))
                {
                    requestBuilder.AppendFormat("{0}\r\n", trace.Url);
                    txtRequests.Text = requestBuilder.ToString();
                }
            }
        }


        public void Error(ErrorItem error)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new ErrorDelegate(Error), error);
            }
            else
            {
                errorBuilder.AppendFormat("{0}\r\n{1}\r\n---------------------------------\r\n", error.Url, error.Error);
                txtError.Text = errorBuilder.ToString();
            }
        }
    }
}
